import * as vant from 'vant'
import * as bsc from '@/contract/bsc'
import * as home from '@/api/home'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const user = computed(() => userStore.user)

let signer: any = null

export const check = async () => {
  if (!window.ethereum) {
    vant.showFailToast({ message: '请安装MetaMask或其他Ethereum钱包扩展。', duration: 3000 })
    return false
  }
  if (!user.value.address) {
    connect()
  }
  const ret = await bsc.checkWallet(user.value.address)
  if (!ret) {
    connect()
  }
}

export const connect = async () => {
  if (!window.ethereum) {
    vant.showFailToast({ message: '请安装MetaMask或其他Ethereum钱包扩展。', duration: 3000 })
    return false
  }
  signer = await bsc.connectWallet()
  const address = await signer.getAddress()
  console.log('signer address:', address)
  if (!address) {
    user.value.address = ''
    return
  }
  await login(address)
}

export const login = async (address: string) => {
  await home
    .login(address)
    .then(async ret => {
      console.log('login success:', ret.data)
      window.sessionStorage.setItem('token', ret.data.address)
      userStore.setUser(ret.data)
      user.value.address = address
      user.value.balance = await getBalance()
      if (user.value.state == 1) {
        user.value.link = `https://www.ng68.app?ref=${address}`
        // user.value.link = `https://www.ng68.app/#/home?ref=${address}`
      } else {
        user.value.link = '请先购买激活'
      }
    })
    .catch(ret => {
      console.log('login error:', ret)
      vant.showFailToast({ message: ret.message, duration: 3000 })
    })
}

// 调用导出的函数
export async function getBalance() {
  return await bsc.getWalletBalance(signer)
}

// 购买
export async function buy(amount: number) {
  if (!signer) {
    vant.showFailToast({ message: '请先连接钱包', duration: 3000 })
    return
  }
  if (user.value.ref == '') {
    vant.showFailToast({ message: '参数错误', duration: 3000 })
    return
  }
  console.log('开始调用 transferBNB...')
  const loading = vant.showLoadingToast({
    message: '购买中...',
    duration: 300000,
    forbidClick: true
  })
  try {
    const ret = await bsc.callTransferBNB(user.value.ref, amount + '')
    console.log('callTransferBNB ret:', ret)
    if (ret) {
      console.log('active start ...')
      await home.active(user.value.address)
      console.log('active completed.')

      console.log('login start ...')
      await login(user.value.address)
      console.log('login completed.')

      loading.close()
      vant.showSuccessToast({ message: '购买成功', duration: 3000 })
    } else {
      loading.close()
      vant.showFailToast({ message: '购买失败', duration: 3000 })
    }
  } catch (error) {
    loading.close()
    console.log('buy error:', error)
    const emsg = JSON.stringify(error)
    // vant.showFailToast({ message: '购买异常:' + emsg, duration: 5000 })
    vant.showToast({ message: '购买异常:' + emsg, wordBreak: 'break-word' })
  }

  console.log('transferBNB 调用完成')
}

export async function getAddress() {
  return await signer.address
}

export async function endTime() {
  return await home.endTime()
}
